﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Web;
using System.Configuration;

namespace fanfu.Common
{
    /// <summary>
    /// 日志类
    /// </summary>
    public static class LogHelper
    {
        /// <summary>
        /// 写日志
        /// </summary>
        /// <param name="textContent">内容</param>
        /// <param name="logType">日志类型</param>
        public static void WriterLog(string textContent, LogType logType)
        {
            //配置文件没有设置时则设置默认路径
            string configPath = ConfigurationManager.AppSettings["LogFilePath"];
            if (string.IsNullOrEmpty(configPath))
                configPath = "Log/";

            //物理路径不存在则创建物理路径
            //加上"~/"解除F5运行时无法映射路径的错误
            string realityPath = HttpContext.Current.Server.MapPath("~/" + configPath); 
            if (!Directory.Exists(realityPath))
                Directory.CreateDirectory(realityPath);

            realityPath += logType.ToString() + ".txt";
            StreamWriter sw = null;
            try
            {
                sw = new StreamWriter(realityPath, true, System.Text.Encoding.Default);
                sw.WriteLine("");
                sw.WriteLine(DateTime.Now.ToString());
                sw.WriteLine("=============================================================================================================================================");
                sw.WriteLine(textContent);
                sw.Close();
            }
            catch (Exception ex)
            {
                if (sw != null)
                    sw.Close();
            }
        }

        /// <summary>
        /// 日志类型
        /// </summary>
        public enum LogType
        {
            /// <summary>
            /// 登录日志
            /// </summary>
            LoginLog,
            /// <summary>
            /// 系统异常
            /// </summary>
            ErrorLog,
        }
    }
}
